<?php
class IndexController extends Controller
{
    public $layout = 'column';
	public function actionIndex()
	{
	    $criteria = new CDbCriteria(array(
	        'order' => 'id desc',
	        'select' => 'id, title, content, add_time',
	        'condition' => 'publish = true',
	    ));
	    if ($cid = (int)$this->getQuery('cid')) {
	        $criteria->addColumnCondition(array('cid' => $cid));
	        $category = Category::model()->findByPk($cid,array('select' => 'name'));
	    }
	    
	    if ($this->getQuery('q')) {
	        $criteria->compare('title', $this->getQuery('q'), true);
	    }
		$dataProvider = new CActiveDataProvider('Post', array(
		    'criteria' => $criteria,
		    'pagination' => array('pageVar' => 'page')
		));
		$this->display(array(
			'dataProvider' => $dataProvider,
		    'category' => (isset($category)) ? $category : false,
		));
	}
	
	public function actionView($id)
	{
	    $model = $this->loadModel($id);
	    $comment = $this->comment($model);
	    $model->autoClickNum();
	    $this->display(array(
	        'model' => $model,
	        'comment' => $comment,
	    ));
	}
	
	public function loadModel($id)
	{
	    $model = Post::model()->findByPk((int)$id);
	    if (null === $model) 
	        throw new CHttpException(404,'The requested page does not exist.');
	    return $model;
	}
	
	public function comment($post)
	{
	    $comment = new Comment();
	    if ($this->getPost('Comment')) {
	        $comment->attributes = $this->getPost('Comment');
	        if ($post->addComment($comment)) {
	            $this->refresh();
	        }
	    }
	    
	    return $comment;
	}
}